package wavedigest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.repackaged.com.google.common.util.Base64;
import com.google.appengine.repackaged.com.google.common.util.Base64DecoderException;

@SuppressWarnings("serial")
public class RegistrationGadget extends HttpServlet
{
	private static final Logger log = Logger.getLogger("RegistrationWidget");
	
	private static final String PARAM_WAVE_ID = "::wid::";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		log.info("get request for gadget");
		
		String wid = null;
		try
		{
			wid = new String(Base64.decode(req.getParameter("wid").getBytes()));
		}
		catch (Base64DecoderException e)
		{
			e.printStackTrace();
			wid = null;
		}
		
		if (null == wid)
			throw new ServletException("expected a wave id");
		
		log.info("wid = " + wid);

		createGadget(wid, resp);
	}

	private void createGadget(String wid, HttpServletResponse resp) throws IOException
	{
		log.info("Creating gadget for wave id:" + wid);

		Map<String, String> params = new HashMap<String, String>();
		params.put(PARAM_WAVE_ID, Base64.encode(wid.getBytes()));
		
		File templateFile = new File("WEB-INF/registerGadget.html");

		resp.setContentType("text/xml");
		createResponse(params, templateFile, resp.getOutputStream());
	}

	private void createResponse(Map<String, String> params, File templateFile, ServletOutputStream outputStream) throws IOException
	{
		String fileData = getFileData(templateFile);

		for (String key : params.keySet())
		{
			fileData = fileData.replace(key, params.get(key));
		}

		log.info("file data:\n\n" + fileData + "\n\n");
		outputStream.write(fileData.getBytes());
	}

	private static String getFileData(File file)
	{
		StringBuilder contents = new StringBuilder();

		try
		{
			BufferedReader input = new BufferedReader(new FileReader(file));
			try
			{
				String line = null; // not declared within while loop
				while ((line = input.readLine()) != null)
				{
					contents.append(line);
					contents.append(System.getProperty("line.separator"));
				}
			}
			finally
			{
				input.close();
			}
		}
		catch (IOException ex)
		{
			ex.printStackTrace();
		}

		return contents.toString();
	}

}
